let that

class DrawTools {
    constructor(map) {
        that = this
        that.map = map
        that.mapDom = map.getCanvasContainer()
        that.coords = []
        that.points = []
        that.polylines = []
        that.polygons = []

        that.map.addSource('draw-point', {
            "type": "geojson",
            "data": that.getGeojson([])
        })
        that.map.addSource('draw-polyline', {
            "type": "geojson",
            "data": that.getGeojson([])
        })
        that.map.addSource('draw-polygon', {
            "type": "geojson",
            "data": that.getGeojson([])
        })
        that.map.addLayer({
            id: 'draw-polyline',
            source: 'draw-polyline',
            type: 'line',
            "paint": {
                "line-width": 3,
                "line-color": "red"
            }
        })

        that.map.addLayer({
            id: 'draw-polygon-fill',
            source: 'draw-polygon',
            type: 'fill',
            "paint": {
                "fill-opacity": 0.3,
                "fill-color": "red"
            }
        })
        that.map.addLayer({
            id: 'draw-polygon-line',
            source: 'draw-polygon',
            type: 'line',
            "paint": {
                "line-width": 3,
                "line-color": "red"
            }
        })

        that.map.addLayer({
            id: 'draw-point',
            source: 'draw-point',
            type: 'circle',
            "paint": {
                'circle-color': 'red',
                'circle-radius': 5
            }
        })

        // 鼠标提示展示 , .setLngLat(coords)
        that.domTips = document.createElement('div')
        that.domTips.classList.add('tool-tips')
        that.toolTips = new mapboxgl.Marker({
            element: that.domTips,
            anchor: 'left',
            offset: [1.6, 0]
        }).setLngLat([-180, -90]).addTo(that.map);

    }

    clickEvent(e) {
        if(!that.type) return
        const {lng, lat} = e.lngLat
        if(that.type === 'point') {
            const point = turf.point([lng, lat])
            that.points.push(point)
            that.map.getSource('draw-point').setData(that.getGeojson(that.points))
        } else {
            that.coords.push([lng, lat])
            // 圆和矩形的绘制
            if(['circle', 'rect'].includes(that.type)) {
                if(that.coords.length === 2) {
                    //1. 圆的
                    if(that.type === 'circle') {
                        that.showCircle(that.coords)
                    }
                    // 2. 矩形
                    if(that.type === 'rect') {
                        that.showRect(that.coords)
                    }
                    that.coords = []
                }
            }
        }
    }

    dblclickEvent(e) {
        if(!that.type) return
        const coords = that.coords.concat([])
        if(that.type === 'polyline') {
            if(coords.length > 1) {
                const lineString = turf.lineString(coords)
                that.polylines.push(lineString)
                that.map.getSource('draw-polyline').setData(that.getGeojson(that.polylines))
            }
        } else if(that.type === 'polygon'){
            if(coords.length > 2) {
                coords.push(coords[0])
                const polygon = turf.polygon([coords])
                that.polygons.push(polygon)
                that.map.getSource('draw-polygon').setData(that.getGeojson(that.polygons))
            }
        }
        that.coords = []
    }

    mousemoveEvent(e) {
        if(!that.type) return
        const {lng, lat} = e.lngLat
        if(that.coords.length === 0) {
            that.domTips.innerText = '点击地图开始绘制'
        } else {
            const coords = that.coords.concat([])
            coords.push([lng, lat])
            if(that.type === 'polyline') {
                if(coords.length > 1) {
                    const lineString = turf.lineString(coords)
                    const polylines = that.polylines.concat([])
                    polylines.push(lineString)
                    that.map.getSource('draw-polyline').setData(that.getGeojson(polylines))
                    that.domTips.innerText = '双击结束绘制'
                }
            } else if(that.type === 'polygon') {
                if(coords.length > 2) {
                    // 显示面积
                    coords.push(coords[0])
                    const polygon = turf.polygon([coords])
                    const polygons = that.polygons.concat([])
                    polygons.push(polygon)
                    that.map.getSource('draw-polygon').setData(that.getGeojson(polygons))
                    that.domTips.innerText = '双击结束绘制'
                } else {
                    const polygons = that.polygons.concat([])
                    that.map.getSource('draw-polygon').setData(that.getGeojson(polygons))

                    const lineString = turf.lineString(coords)
                    const polylines = that.polylines.concat([])
                    polylines.push(lineString)
                    that.map.getSource('draw-polyline').setData(that.getGeojson(polylines))
                    that.domTips.innerText = '继续点击绘制多边形'
                }
            } else {
                if(coords.length === 2) {
                    // 展示临时的绘制结果
                    //1. 圆的
                    if(that.type === 'circle') {
                        that.showCircle(coords, true)
                    }
                    // 2. 矩形
                    if(that.type === 'rect') {
                        that.showRect(coords, true)
                    }
                }
            }
        }
        that.toolTips.setLngLat([lng, lat])
    }

    showCircle(coords, isTemp) {
        const from = turf.point(coords[0]);
        const to = turf.point(coords[1]);
        const distance = turf.distance(from, to);
        const polygon = turf.buffer(from, distance)
        const polygons = isTemp ?  that.polygons.concat([]) :  that.polygons
        polygons.push(polygon)
        that.map.getSource('draw-polygon').setData(that.getGeojson(polygons))
    }

    showRect(coords, isTemp) {
        const from = coords[0]
        const to = coords[1]
        const bbox = [from[0], from[1], to[0], to[1]];
        const polygon = turf.bboxPolygon(bbox);
        const polygons = isTemp ?  that.polygons.concat([]) :  that.polygons
        polygons.push(polygon)
        that.map.getSource('draw-polygon').setData(that.getGeojson(polygons))
    }

    /**
     * 激活测量
     * @param type - 绘制类型，point，polyline，polygon，circle， rect
     */
    activeDraw(type) {
        that.coords = []
        that.type  =  type
        // that.map.getSource('draw-point').setData(that.getGeojson([]))
        // that.map.getSource('draw-polyline').setData(that.getGeojson([]))
        // that.map.getSource('draw-polygon').setData(that.getGeojson([]))
        that.mapDom.style.cursor = 'crosshair'
        map.on('click', that.clickEvent)
        map.on('dblclick', that.dblclickEvent)
        map.on('mousemove', that.mousemoveEvent)
    }

    /**
     *
     */
    deactiveDraw() {
        that.stopDraw()
        that.toolTips.setLngLat([-180, -90])

    }

    stopDraw() {
        that.coords = []
        that.type  =  ''
        that.mapDom.style.cursor = ''
        map.off('click', that.clickEvent)
        map.off('dblclick', that.dblclickEvent)
        map.off('mousemove', that.mousemoveEvent)
        that.toolTips.setLngLat([-180, -90])
    }

    clearDraw() {
        that.deactiveDraw()
        that.points = []
        that.polylines = []
        that.polygons = []
        that.map.getSource('draw-point').setData(that.getGeojson([]))
        that.map.getSource('draw-polyline').setData(that.getGeojson([]))
        that.map.getSource('draw-polygon').setData(that.getGeojson([]))
    }

    getGeojson(features) {
        return {
            "type": "FeatureCollection",
            features: features
        }
    }
}